// api/user_api/password_login.go
package user_api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/models/ctype"
	"muziai-server/service/common"
	"muziai-server/utils/pwd"
	"muziai-server/utils/res"
)

type PasswordLoginRequest struct {
	Val       string               `json:"val" binding:"required"`
	Pwd       string               `json:"pwd" binding:"required"`
	LoginType ctype.RegisterSource `json:"loginType" binding:"required,oneof=1 2 4"`
	Captcha   string               `json:"captcha" binding:"required"`
	CaptchaID string               `json:"captchaID" binding:"required"`
}

func (u UserApi) PasswordLoginView(c *gin.Context) {
	var cr PasswordLoginRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}

	log := common.GetLog(c)
	log.ShowResponse()

	log.SetItem("输入的验证码", cr.Captcha)
	log.SetItem("输入的用户名", cr.Val)
	log.SetItem("登录方式", cr.LoginType)
	log.SetTitle("用户登录")

	if cr.Captcha == "" || cr.CaptchaID == "" {
		res.FailWithMsg(c, "请输入图形验证码")
		return
	}

	ok := store.Verify(cr.CaptchaID, cr.Captcha, true)
	if !ok {
		res.FailWithMsg(c, "验证码校验失败")
		return
	}

	var user models.UserModel
	lo := global.Config.SiteInfo.Login
	queryKey := ""
	var name string
	switch cr.LoginType {
	case ctype.UsernameRegister:
		name = "用户名"
		queryKey = "username = ?"
		if !lo.IsUsernameLogin {
			res.FailWithMsg(c, "管理员未开启用户名+密码登录")
			return
		}
	case ctype.EmailRegister:
		name = "邮箱"
		queryKey = "email = ?"
		if !lo.IsEmailLogin {
			res.FailWithMsg(c, "管理员未开启邮箱+密码登录")
			return
		}
		//case ctype.TelRegister:
		//	name = "手机号"
		//	queryKey = "tel = ?"
		//	if !lo.IsTelLogin {
		//		res.FailWithMsg(c, "管理员未开启手机号+密码登录")
		//		return
		//	}
	}

	err = global.DB.Take(&user, queryKey, cr.Val).Error
	if err != nil {
		// 一定不要写用户不存在，这样的话攻击者就可以根据登录接口，判断你系统的用户了
		res.FailWithMsg(c, fmt.Sprintf("%s或密码错误", name))
		return
	}

	// 判断密码
	if !pwd.ComparePasswords(user.Password, cr.Pwd) {
		res.FailWithMsg(c, fmt.Sprintf("%s或密码错误", name))
		return
	}
	u.UserService.UserLogin(c, user)

}
